package msgPoint

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/robfig/cron/v3"
	"im/app/conf"
	"im/app/models"
	"im/app/util"
	"im/rabbitmq"
	"time"
)

func MsgPoint(c *cron.Cron) {
	c.AddFunc("*/30 * * * * *", func() {
		fmt.Println("定时任务运行了--------:",time.Now().Format("2006-01-02 15:04:05"))
		pool,err := rabbitmq.RabbitPoolServe.GetPool()
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		pool.CreateExTopic("msg","point")
		pool.CreateQueuen("point")
		msgs, err := pool.CreateCustmer("", 10)
		if err != nil {
			fmt.Println("rabbit point队列参数接受失败!")
			return
		}
		for d := range msgs {
			msgCount := make(map[string]*models.Messages)
			fmt.Println("接受到的消息是:", string(d.Body))
			if len(string(d.Body)) > 0 {
				msg := models.Messages{}
				_ = json.Unmarshal(d.Body, &msg)
				key := util.GetMd5String(msg.MsgID)
				msgCount[key] = &msg
			}
			err = batchInster(msgCount)
			if err != nil {
				fmt.Println("rabbit point队列数据插入失败!")
			}else {
				d.Ack(false)
			}
		}

		fmt.Println("定时任结束了--------:")
	})
}

// batchInster
func batchInster(msgCount map[string]*models.Messages) error {
	var buffer bytes.Buffer
	sql := "insert into `messages` (`msg_id`,`user_id`,`dst_id`,`content`,`pic`,`is_r`,`created_at`,`updated_at`) values "
	if _,err := buffer.WriteString(sql); err != nil {
		return err
	}
	leng := len(msgCount)
	i := 0
	for _,msg := range msgCount {
		// msg := models.Messages{}
		// _ = json.Unmarshal([]byte(v), &msg)
		if msg.Pic == "" {
			msg.Pic = "pic"
		}
		if i == leng-1 {
			buffer.WriteString(fmt.Sprintf("('%s',%d,%d,'%s','%s',%d,%d,%d);",msg.MsgID,msg.UserID,msg.DstId,msg.Content,msg.Pic,msg.IsR,msg.CreatedAt,msg.UpdatedAt))
		}else {
			buffer.WriteString(fmt.Sprintf("('%s',%d,%d,'%s','%s',%d,%d,%d),",msg.MsgID,msg.UserID,msg.DstId,msg.Content,msg.Pic,msg.IsR,msg.CreatedAt,msg.UpdatedAt))
		}
		i++
	}
	fmt.Println(buffer.String())
	conf.Mdb.Exec(buffer.String())
	return nil
}
